/**
 * Notes: API请求转发中心
 * Ver : WeCollege Server API 1.0.0
 * Date: 2025-01-27
 * Description: 统一管理所有后端API请求，支持云函数和自建服务器切换
 */

const helper = require('./helper.js');
const cacheHelper = require('./cache_helper.js');
const constants = require('../comm/constants.js');
const pageHelper = require('./page_helper.js');
const PassportBiz = require('../comm/biz/passport_biz.js');

// API配置
const API_CONFIG = {
  // 服务器配置
  SERVER: {
    BASE_URL: 'http://localhost:8086',  // 后端服务器地址
    TIMEOUT: 10000,                     // 请求超时时间
    USE_SERVER: true,                   // 是否使用自建服务器 (false=云函数, true=自建服务器)
  },
  
  // 响应码定义
  CODE: {
    SUCCESS: 200,        // 成功
    SERVER_ERROR: 500,   // 服务器错误
    LOGIC_ERROR: 1600,   // 逻辑错误
    DATA_ERROR: 1301,    // 数据校验错误
    AUTH_ERROR: 401,     // 认证错误
  }
};

/**
 * 统一请求方法
 * @param {string} endpoint - API端点
 * @param {object} data - 请求数据
 * @param {object} options - 请求选项
 * @returns {Promise} 请求结果
 */
async function request(endpoint, data = {}, options = {}) {
  const {
    method = 'POST',
    title = '加载中...',
    showLoading = true,
    showError = true
  } = options;

  // 显示加载提示
  if (showLoading) {
    if (title === 'bar') {
      wx.showNavigationBarLoading();
    } else {
      wx.showLoading({ title, mask: true });
    }
  }

  try {
    let result;
    
    if (API_CONFIG.SERVER.USE_SERVER) {
      // 使用自建服务器
      result = await requestServer(endpoint, data, method);
    } else {
      // 使用云函数 (保持兼容)
      result = await requestCloud(endpoint, data);
    }

    return result;
    
  } catch (error) {
    console.error('API请求失败:', error);
    
    if (showError) {
      wx.showModal({
        title: '温馨提示',
        content: error.message || '网络请求失败，请稍后重试',
        showCancel: false
      });
    }
    
    throw error;
    
  } finally {
    // 隐藏加载提示
    if (showLoading) {
      if (title === 'bar') {
        wx.hideNavigationBarLoading();
      } else {
        wx.hideLoading();
      }
    }
  }
}

/**
 * 自建服务器请求
 */
async function requestServer(endpoint, data, method) {
  return new Promise((resolve, reject) => {
    // 获取认证token
    const token = getAuthToken();
    
    // 构建请求头
    const header = {
      'Content-Type': 'application/json',
    };
    
    if (token) {
      header['Authorization'] = `Bearer ${token}`;
    }

    // 构建完整URL
    const url = `${API_CONFIG.SERVER.BASE_URL}${endpoint}`;
    
    wx.request({
      url,
      method,
      data,
      header,
      timeout: API_CONFIG.SERVER.TIMEOUT,
      success: (res) => {
        const { statusCode, data: responseData } = res;
        
        if (statusCode === 200) {
          if (responseData.code === API_CONFIG.CODE.SUCCESS) {
            resolve(responseData);
          } else {
            // 处理业务错误
            handleBusinessError(responseData, reject);
          }
        } else {
          reject(new Error(`HTTP ${statusCode}: 服务器响应异常`));
        }
      },
      fail: (error) => {
        console.error('网络请求失败:', error);
        reject(new Error('网络连接失败，请检查网络设置'));
      }
    });
  });
}

/**
 * 云函数请求 (兼容旧版本)
 */
async function requestCloud(route, params) {
  return new Promise((resolve, reject) => {
    const token = getCloudToken();
    const PID = pageHelper.getPID();

    wx.cloud.callFunction({
      name: 'mcloud',
      data: { route, token, PID, params },
      success: (res) => {
        if (res.result.code === 200) {
          resolve(res.result);
        } else {
          handleBusinessError(res.result, reject);
        }
      },
      fail: (error) => {
        reject(new Error('云函数调用失败'));
      }
    });
  });
}

/**
 * 获取认证Token
 */
function getAuthToken() {
  const user = cacheHelper.get(constants.CACHE_TOKEN);
  return user?.token || '';
}

/**
 * 获取云函数Token (兼容)
 */
function getCloudToken() {
  const user = cacheHelper.get(constants.CACHE_TOKEN);
  return user?.id || '';
}

/**
 * 处理业务错误
 */
function handleBusinessError(result, reject) {
  const { code, msg } = result;
  
  switch (code) {
    case API_CONFIG.CODE.AUTH_ERROR:
      // 认证失败，跳转登录
      PassportBiz.clearToken();
      wx.reLaunch({
        url: '/pages/my/login/my_login'
      });
      break;
      
    default:
      reject(new Error(msg || '请求处理失败'));
  }
}

/**
 * 切换API模式
 */
function switchApiMode(useServer = true) {
  API_CONFIG.SERVER.USE_SERVER = useServer;
  console.log(`API模式已切换为: ${useServer ? '自建服务器' : '云函数'}`);
}

/**
 * 设置服务器地址
 */
function setServerUrl(url) {
  API_CONFIG.SERVER.BASE_URL = url;
  console.log(`服务器地址已设置为: ${url}`);
}

// 导出API配置和方法
module.exports = {
  API_CONFIG,
  request,
  switchApiMode,
  setServerUrl,
  
  // 便捷方法
  get: (endpoint, options) => request(endpoint, {}, { ...options, method: 'GET' }),
  post: (endpoint, data, options) => request(endpoint, data, { ...options, method: 'POST' }),
  put: (endpoint, data, options) => request(endpoint, data, { ...options, method: 'PUT' }),
  delete: (endpoint, options) => request(endpoint, {}, { ...options, method: 'DELETE' }),
};